import * as THREE from 'three'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'
let scene, camera, renderer, controls

/* 
  旋转效果
*/
function init() {
  scene = new THREE.Scene()
  camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
  camera.position.set(0, 0, 5)
  renderer = new THREE.WebGLRenderer({ antialias: true })
  renderer.setSize(window.innerWidth, window.innerHeight)
  document.body.appendChild(renderer.domElement)

  controls = new OrbitControls(camera, renderer.domElement)
  controls.enableDamping = true

  const axesHelper = new THREE.AxesHelper(5)
  scene.add(axesHelper)
};
let material;
function createBasic () {
  // 1. 创建平面
  const geometry = new THREE.PlaneGeometry(1, 1, 64, 64)
  // 自己自定义属性position2，然后赋值为geometry.attributes.position
  // 2. 创建材质
  material = new THREE.ShaderMaterial({
    vertexShader: `
      uniform float myTime;
      void main () {
        float angle = myTime;
        float radian = radians(angle);
        float cosV = cos(radian);
        float sinV = sin(radian);
        // mat4 mx = mat4(1,0,0,0, 0,cosV,-sinV,0, 0,sinV,cosV,0, 0,0,0,1); // 绕着x轴旋转
        // mat4 mx = mat4(cosV,sinV,0,0, sinV,cosV,0,0, 0,0,1,0, 0,0,0,1); // 绕着y轴旋转
        mat4 mx = mat4(cosV,0,sinV,0, 0,1,0,0, -sinV,0,cosV,0, 0,0,0,1); // 绕着z轴旋转
        vec4 v = mx * vec4(position, 1.0);

        gl_Position = projectionMatrix * viewMatrix * modelMatrix * v;
      }
    `,
    // 片元着色器
    // 上黑下白的效果
    fragmentShader: `
      void main () {
        gl_FragColor = vec4(0, 1.0, 0, 0.9);
      }
    `,
    uniforms: {
      myTime: {
        value: 0 // 初始值位移x轴2.0个单位
      }
    },
    side: THREE.DoubleSide
  })
  // 3. 创建物体
  const mesh = new THREE.Mesh(geometry, material)
  scene.add(mesh)
}

function renderLoop(t) {
  console.log(t, 't');
  // 把时间数值传入到材质的uniforms变量中
  material.uniforms.myTime.value = t / 20;
  renderer.render(scene, camera)
  controls.update()
  requestAnimationFrame(renderLoop)
}

init()
createBasic()
renderLoop() 

